package com.universal.frame.generalutils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * RoreyDiu
 * Created by Administrator on 2016/11/25 0025.
 */

public class CameraUtil {

    /**
     * @throws
     * @Description: 得到图片处理 界面重写 onActivityResult 调用此方法
     * @return: Bitmap
     */

    public static Bitmap getBitmapFromActivityResult(Activity activity, int requestCode,
                                                     int resultCode, Intent data) {
        // 照相機返回
        if (requestCode == Constants.PHOTO_REQUEST_CAMERA
                && resultCode == Activity.RESULT_OK && data != null) {
            Uri uri = data.getData();
            if (uri == null) {
                // use bundle to get data
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    Bitmap photo = (Bitmap) bundle.get("data"); // get bitmap
                    // spath :生成图片取个名字和路径包含类型
                    // 压缩
                    return compressBitmap(photo, 720);
                }
            } else {
                try {

                    Bitmap image = MediaStore.Images.Media.getBitmap(
                            activity.getContentResolver(), uri);
                    if (image != null) {
                        // 反回压缩过的bitmap
                        return compressBitmap(image, 720);
                    }
                } catch (Exception e) {
                }
            }
        } else if (requestCode == Constants.PHOTO_REQUEST_GALLERY
                && resultCode == Activity.RESULT_OK && data != null) // 相册返回
        {
            Uri uri = data.getData();
            if (uri == null) {
                // use bundle to get data
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    Bitmap photo = (Bitmap) bundle.get("data"); // get bitmap
                    // spath :生成图片取个名字和路径包含类型
                    // 压缩
                    return compressBitmap(photo, 720);
                }
            } else {
                try {
                    Bitmap image = MediaStore.Images.Media.getBitmap(
                            activity.getContentResolver(), uri);
                    if (image != null) {
                        // 反回压缩过的bitmap
                        return compressBitmap(image, 720);
                    }
                } catch (Exception e) {
                }
            }
        }
        return null;
    }

    /**
     * 根据传入的maxSize压缩图片
     */
    public static Bitmap compressBitmap(Bitmap bitmap, int maxSize) {
        int mWidth = bitmap.getWidth();
        int mHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = 1;
        float scaleHeight = 1;
        if (mWidth <= mHeight) {
            scaleWidth = maxSize / (float) mWidth;
            scaleHeight = maxSize / (float) mHeight;
            scaleWidth = scaleHeight;
        } else {
            scaleWidth = maxSize / (float) mWidth;
            scaleHeight = maxSize / (float) mHeight;
            scaleHeight = scaleWidth;
        }
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight,
                matrix, true);

//         bitmap.recycle();
        return newBitmap;
    }

    /**
     * 将Bitmap转换成File的方法
     */
    public static File bitmapTofile(Bitmap bmp) throws IOException {
        String filename = Constants.IMAGE_BASE_NAME + System.currentTimeMillis()
                + Constants.IMAGE_BASE_TYPE;
        File file = new File(Constants.IMAGE_PATH + filename);
        if (!file.exists()) {
            File dir = new File(Constants.IMAGE_PATH);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            file.createNewFile();
        }
        Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
        int quality = 40;
        OutputStream stream = null;
        try {
            stream = new FileOutputStream(Constants.IMAGE_PATH + filename);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        boolean result = bmp.compress(format, quality, stream);

        if (result) {
//            bmp.recycle();
            return file;
        }

        return null;
    }

    public static Bitmap decodeBitmap(String path,double filesize){
        BitmapFactory.Options options = new BitmapFactory.Options();
       if(filesize >45.5){
            options.inSampleSize = 20;
        }
       else if(filesize > 30.5){
           options.inSampleSize = 15;
       }
       else if(filesize > 20.5){
           options.inSampleSize = 10;
       }
       else if(filesize > 17.5){
           options.inSampleSize = 10;
       }
       else if(filesize > 14.5){
           options.inSampleSize = 6;
       }
       else if(filesize > 11.5){
           options.inSampleSize = 5;
       }
       else if(filesize > 8.5){
            options.inSampleSize = 4;
        } else if(filesize > 5.5){
            options.inSampleSize = 3;
        }else if(filesize > 3){
            options.inSampleSize = 2;
        }else if(filesize > 1.5){
            options.inSampleSize = 1;
        }else{
            options.inSampleSize = 0;
        }
        options.inJustDecodeBounds = false;
//        options.inPreferredConfig = Bitmap.Config.ARGB_4444;
        // 注意这次要把options.inJustDecodeBounds 设为 false,这次图片是要读取出来的。&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
//        int w = bitmap.getWidth();
//        int h = bitmap.getHeight();
//        Log.i("tag","缩略图高度：" + h + "宽度:" + w);
        return bitmap;
    }

    public static Bitmap decodeBitmap(String path){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        options.inJustDecodeBounds = false;
//        options.inPreferredConfig = Bitmap.Config.ARGB_4444;
        // 注意这次要把options.inJustDecodeBounds 设为 false,这次图片是要读取出来的。&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
//        int w = bitmap.getWidth();
//        int h = bitmap.getHeight();
//        Log.i("tag","缩略图高度：" + h + "宽度:" + w);
        return bitmap;
    }

    /**
     * 图片质量压缩（质量参数)
     * @param quality 质量参数 百分之多少 例如:0.6  0.7
     * @return
     */
    public static Bitmap compressImage(String path, float quality)
    {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        options.inJustDecodeBounds = false;
//        options.inPreferredConfig = Bitmap.Config.ARGB_4444;
        // 注意这次要把options.inJustDecodeBounds 设为 false,这次图片是要读取出来的。&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
        Bitmap image = BitmapFactory.decodeFile(path, options);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, (int)quality*100, baos);
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        return BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
    }

    /**
     * Get bitmap from specified image path
     *
     * @param imgPath
     * @return
     */
    public static Bitmap getBitmap(String imgPath) {
        // Get bitmap through image path
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = false;
        newOpts.inPurgeable = true;
        newOpts.inInputShareable = true;
        // Do not compress
        newOpts.inSampleSize = 1;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeFile(imgPath, newOpts);
    }
}
